#!/bin/bash

echo "🚀 开始重新构建和部署项目..."

# 停止现有服务
echo "📛 停止现有服务..."
pm2 stop all 2>/dev/null || true

# 重新构建前端
echo "🔨 构建前端..."
cd /Users/zyu/leo/ignite-fun/frontend
npm run build

if [ $? -eq 0 ]; then
    echo "✅ 前端构建成功"
else
    echo "❌ 前端构建失败"
    exit 1
fi

# 重新构建后端
echo "🔨 构建后端..."
cd /Users/zyu/leo/ignite-fun/backend
npm run build

if [ $? -eq 0 ]; then
    echo "✅ 后端构建成功"
else
    echo "❌ 后端构建失败"
    exit 1
fi

# 重新加载nginx配置
echo "🔄 重新加载nginx配置..."
sudo nginx -t && sudo nginx -s reload

if [ $? -eq 0 ]; then
    echo "✅ Nginx配置重新加载成功"
else
    echo "❌ Nginx配置重新加载失败"
    exit 1
fi

# 启动服务
echo "🚀 启动服务..."
cd /Users/zyu/leo/ignite-fun

# 检查PM2是否安装
if ! command -v pm2 &> /dev/null; then
    echo "⚠️  PM2 未安装，使用普通启动方式..."
    
    # 使用nohup在后台启动服务
    echo "🚀 启动后端服务..."
    cd backend
    nohup npm run start:prod > ../logs/backend.log 2>&1 &
    BACKEND_PID=$!
    echo "后端PID: $BACKEND_PID"
    
    echo "🚀 启动前端服务..."
    cd ../frontend
    nohup npm start > ../logs/frontend.log 2>&1 &
    FRONTEND_PID=$!
    echo "前端PID: $FRONTEND_PID"
    
    echo "✅ 服务已启动 (后端PID: $BACKEND_PID, 前端PID: $FRONTEND_PID)"
else
    echo "🚀 使用PM2启动服务..."
    pm2 start ecosystem.config.js --env production
    echo "✅ PM2服务已启动"
fi

echo "✅ 部署完成！"

# 测试WebSocket连接
echo "🧪 测试WebSocket连接..."
sleep 5

echo "📋 检查服务状态:"
pm2 status

echo "🌐 应用访问地址:"
echo "  - 生产环境: https://c4pad.fun"
echo "  - IP访问: http://104.129.59.158"

echo ""
echo "🔧 如果聊天室仍然无法工作，请检查："
echo "  1. WebSocket连接: wss://c4pad.fun/realtime"
echo "  2. 浏览器开发者工具的网络选项卡"
echo "  3. 后端服务日志: pm2 logs backend"
echo "  4. 前端服务日志: pm2 logs frontend"
